<?php
namespace Api\Controller;
use Think\Controller;
use Think\Vender;
use Think\Model;
class WxtokenController extends Controller{ 

	//获取公众号access_token
	function get_token(){
	    $access_obj = M('wxtoken')->field(true)->find(); //获取access_token表的所有字段
		$now = intval(time());					  //获取系统当前时间并且转化成整数
	    if($access_obj && intval($access_obj['time']) > ($now-7200)){		//access_token的有效期为2小时，用存进去的时间对比现在减去7200秒
	    	return $access_obj['wxtoken']; 									//如果存进去的时间大于$now-7200说明没有过期
	    }else{
	    	$appid='wx0b27ff95a3a3c401';
	    	$appsecret='bb107f7d5b7cd188a2e2682468e104d3';
	    	$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret;
	        $json = json_decode(HttpRequst($url));		//返回一个json格式的对象	
	    	 if(isset($json->access_token) && $json->access_token){
	             if($access_obj){																									//如果access_token有数据，进行修改
	                 M('wxtoken')->where(array('id'=>$access_obj['id']))->save(array('wxtoken'=>$json->access_token,'time'=>$now)); //$this当前数据表模型
	             }else{																												//没有数据添加数据
	                 M('wxtoken')->add(array('wxtoken'=>$json->access_token,'time'=>$now));
	             }
	             return $json->access_token;
	         }else{
	             print_r(array('errcode' => $json->errcode, 'access_token' => $json->errmsg));										//没有获取到token，返回错误信息
	         }
	    }
	}

	public function get_wxuserinfo($wxtoken,$openid){
        // $to='11_xZGWx6KpHf1ooXaTV-xO7u5J3BpwUG-qpwolFojbmjucZWa2VdSCL2NVm1G28q_pofX_xKdjOIErhOt5l2YCFOGf-i84E6XxrzeSpkh1VcvncbQoimSngAk6LBv5JAf-1iMWkX9ru2OF36LkYSAiAIATNV';
        // $op='oWWpO0sEJ67whD7p8khIs1DXjGig';
        // $userinfourl="https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$to."&openid=".$op."&lang=zh_CN";
        $userinfourl="https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$wxtoken."&openid=".$openid."&lang=zh_CN";
        $data = file_get_contents($userinfourl);
        $arr = json_decode($data,true);
        $datas['openid'] = $arr['openid']; 
        $datas['nickname'] = $arr['nickname']; 
        $datas['sex'] = $arr['sex']; 
        $datas['province'] = $arr['province']; 
        $datas['city'] = $arr['city']; 
        $datas['headimgurl'] = $arr['headimgurl']; 
        $datas['unionid'] = $arr['unionid']; 
        $datas['subscribe'] = $arr['subscribe']; 
        $datas['subscribe_time'] = $arr['subscribe_time'];
        $id=M('wxuserinfo')->where(array('openid'=>$datas['openid']))->find();
        if(empty($id)){
        	M('wxuserinfo')->add($datas);
        }
	}
}